package com.example.demo.Gmail.controller;


import com.example.demo.Gmail.Handle.GmailHandle;
import com.example.demo.Gmail.Handle.proxyHandler;
import com.example.demo.Gmail.Util.MakeUserUtil;
import com.example.demo.Gmail.Util.ScopesUtil;
import com.example.demo.Gmail.model.UserModel;
import com.example.demo.Gmail.service.UserService;
import com.example.demo.Gmail.threadFactory.importThread;
import com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.*;

@Controller
@Api(description="用户登陆接口")
public class UserController {
    //private final String IP="https://www.zhangxuan321.com/getToken";
    private final String IP="http://localhost/getToken";
    private static Logger logger = LoggerFactory.getLogger("UserController");
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static  List<String> SCOPES = Lists.newArrayList();
    private static final String CREDENTIALS_FILE_PATH = "/credentialsproxy.json";
    @Autowired
    UserService userService;

    @Autowired
    ScheduledExecutor scheduledExecutor;

    @ApiOperation(value = "oauth2授权接口")
    @GetMapping("authorization")
    public String authorization(@RequestParam String userName) throws GeneralSecurityException, IOException {
            InputStream in = GmailHandle.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
            GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
            final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
            SCOPES= ScopesUtil.makeScopes();
            GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES).setAccessType("online").build();
            AuthorizationCodeRequestUrl authorizationUrl =
                    flow.newAuthorizationUrl().setRedirectUri(IP);
            String url="https://accounts.google.com/o/oauth2/auth?access_type="+ ((GoogleAuthorizationCodeRequestUrl) authorizationUrl).getAccessType()
                    +"&client_id="+authorizationUrl.getClientId()+"&redirect_uri="+authorizationUrl.getRedirectUri()
                    +"&response_type="+authorizationUrl.getResponseTypes()+"&scope="+authorizationUrl.getScopes()+"&state="+userName;
            return "redirect:"+url;

    }
    @ApiOperation(value = "回调接口，获取accessToken和refreshToken,前端不用做处理",hidden = true)
    @GetMapping("getToken")
    public String returnUrl(@RequestParam String code,@RequestParam String state) throws Exception {
        //大陆环境需要加代理
        proxyHandler.proxy();
        InputStream in = GmailHandle.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
        // Build flow and trigger user authorization request.
        final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES).setAccessType("offline").build();
      try {
          TokenResponse response=  flow.newTokenRequest(code).setRedirectUri(IP).execute();
          System.err.println(response.getRefreshToken());
          UserModel user= MakeUserUtil.makeUser(response,state);
          //判断登陆的google邮箱是否有人登陆
          if (userService.getUser(user.getEmailAddress())!=null){
              //更新AccessToken
              userService.updateAccessToken(user);
              return "redirect:http://localhost/login?emailAddress="+user.getEmailAddress();
               //return "redirect:https://www.zhangxuan321.com/login?emailAddress="+user.getEmailAddress();
          }else {
              userService.insert(user);
              new Thread(new importThread(userService,user,scheduledExecutor,"INBOX"),user.getEmailAddress()+"INBOX").start();
              new Thread(new importThread(userService,user,scheduledExecutor,"SENT"),user.getEmailAddress()+"SENT").start();
              return "redirect:http://localhost/login?emailAddress="+user.getEmailAddress();
             // return "redirect:https://www.zhangxuan321.com/login?emailAddress="+user.getEmailAddress();
          }
      }catch (Exception e){
          logger.info(e.getMessage());
          return e.getMessage();
      }
    }
    @ApiOperation(value = "登录页面回调",hidden = true)
    @GetMapping("login")
    //@ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam( name = "emailAddress", value = "邮箱地址", required = true, dataType = "String"),
    })
    public String login(@RequestParam String emailAddress){

        return "login";
       /* GmailServiceResponse response=new GmailServiceResponse();
        UserModel user=   userService.getUser(emailAddress);
        if (user==null){
           response.setMsg("当前邮箱尚未授权，请转到授权页面");
           return response;
        }else {
            response.setData(user.getEmailAddress());
            return response;
        }
    */
    }
}
